package com.demo.widget.provider;

import com.demo.widget.ResourceTable;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.app.Context;

import java.security.SecureRandom;

public class StackLayoutMangerProvider extends BaseItemProvider {
    Context mContext;
    String[] titles;
    SecureRandom random;

    public StackLayoutMangerProvider(Context context, String[] titles) {
        this.mContext = context;
        this.titles = new String[titles.length];
        System.arraycopy(titles, 0, this.titles, 0, titles.length);
        this.random = new SecureRandom();
    }

    @Override
    public int getCount() {
        return titles != null ? titles.length : 0;
    }

    @Override
    public String getItem(int i) {
        return titles != null ? titles[i] : null;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        ViewHolder viewHolder;
        if (component == null) {
            component = LayoutScatter.getInstance(mContext).parse(
                    ResourceTable.Layout_item_stack_card, componentContainer, false);
            viewHolder = new ViewHolder();
            viewHolder.text = (Text) component.findComponentById(ResourceTable.Id_tv);
            component.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) component.getTag();
        }
        ShapeElement shapeElement = new ShapeElement();
        shapeElement.setRgbColor(new RgbColor(
                random.nextInt(255),
                random.nextInt(255),
                random.nextInt(255),
                255));
        component.setBackground(shapeElement);
        viewHolder.text.setText(getItem(i));
        return component;
    }

    private static class ViewHolder {
        private Text text;
    }
}
